package no.sachmuld.methodcombination.examples.reflection.clossimplestyle.equalshashcode.v2;

import no.sachmuld.methodcombination.api.BehaviourChain;
import no.sachmuld.methodcombination.api.reflection.component.AbstractMethodCombination;
import no.sachmuld.methodcombination.api.reflection.component.DelegatingMethodCombination;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 *
 */
public class HashCode<B extends HashCodeBehaviour> extends DelegatingMethodCombination<B, Integer> {

    @Override
    public HashCode build(final Class behaviourClass, Method targetMethod) {

        executedBy(new AbstractMethodCombination<B, Integer>() {
            @Override
            public Integer execute(Object targetObject, BehaviourChain<? extends B> behaviourChain, final Object... parameters) {

                final List<Integer> all = new ArrayList<>();

                for (B behaviour : behaviourChain.topDown()) {
                    List<Integer> result = behaviour.hashCodes();
                    all.addAll(result);
                }
                int hashCode = 0;
                for (int h : all) {
                    hashCode = 31 * hashCode + h;
                }
                return hashCode;
            }
        });

        return this;

    }


}
